package cn.safeness.web.conf;

import cn.safeness.entity.system.account.ManagerEntity;
import cn.safeness.entity.system.account.RoleEntity;
import cn.safeness.repo.AccountRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

/**
 * @Program management
 * @Description 自定义spring security UserDetails
 * @Anthor vinson
 * @Create 2018-02-27 14:59
 */
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    AccountRepo accountRepo;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException,NullPointerException {

        ManagerEntity user = accountRepo.selectAccountByName(name);
        Set<RoleEntity> role = accountRepo.selectRoleById(user.getId());

        if (user == null) {
            throw new UsernameNotFoundException("username " + name + " not found");
        }

        // SecurityUser实现UserDetails并将SUser的Email映射为username
        SecurityUser securityUser = new SecurityUser(user);
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (RoleEntity r : role) {
            authorities.add(new SimpleGrantedAuthority(r.getName().trim()));
        }
        securityUser.setAuthorities(authorities);
        return securityUser;
    }


}

